#include "picturemodel.h"

#include "databasemanager.h"
#include "album.h"
#include "albummodel.h"
#include "picture.h"

PictureModel::PictureModel(const AlbumModel &albumModel, QObject *parent):
    QAbstractListModel (parent),
    mDb(DatabaseManager::instance()),
    mAlbumId(-1),
    mPictures(new std::vector<std::unique_ptr<Picture>>())
{
    connect(&albumModel, &AlbumModel::rowsRemoved, this, &PictureModel::deletePictureForAlbum);
}

QModelIndex PictureModel::addPicture(const Picture &picture)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    auto newPicture = std::make_unique<Picture>();
    newPicture->set_file_url(picture.file_url());
    mDb.m_picture_dao.add_picture_in_album(mAlbumId, *newPicture);
    mPictures->push_back(std::move(newPicture));
    endInsertRows();

    return index(rowCount(), 0);
}

void PictureModel::setAlbumId(int albumId)
{
    beginResetModel();
    mAlbumId = albumId;
    loadPicture(mAlbumId);
    endResetModel();
}

void PictureModel::clearAlbum()
{
    mDb.m_picture_dao.remove_picture_for_album(mAlbumId);
}

int PictureModel::rowCount(const QModelIndex &) const
{
    return int(mPictures->size());
}

QVariant PictureModel::data(const QModelIndex &index, int role) const
{
    if( !isIndexValid(index) ) {
        return QVariant();
    }

    const Picture& picture = *mPictures->at(int(index.row()));
    switch (role) {
        case Qt::DisplayRole:
            return picture.file_url().fileName();
            break;

        case PictureModel::UrlRole:
            return picture.file_url();
            break;

        case PictureModel::FilePathRole:
            return picture.file_url().toLocalFile();
            break;


        default:
            return QVariant();
    }
}

bool PictureModel::removeRows(int row, int count, const QModelIndex &parent)
{
    if( row < 0
            || row >= rowCount()
            || count < 0
            || row + count > rowCount() )
    {
        return false;
    }

    beginRemoveRows(parent, row, row+count-1);
    int countLeft = count;
    while(countLeft--) {
        mDb.m_picture_dao.remove_picture(mPictures->at(size_t(row))->id());
    }
    mPictures->erase(mPictures->begin()+row, mPictures->begin()+row+count);
    endRemoveRows();
    return true;
}

void PictureModel::deletePictureForAlbum()
{
    beginResetModel();
    mPictures.reset(new std::vector<std::unique_ptr<Picture>>());
    mDb.m_picture_dao.remove_picture_for_album(mAlbumId);
    endResetModel();
}

void PictureModel::loadPicture(int albumId)
{
    if(albumId <= 0) {
        mPictures.reset(new std::vector<std::unique_ptr<Picture>>());
        return;
    }
    mPictures = mDb.m_picture_dao.pictures_for_album(albumId);
}

bool PictureModel::isIndexValid(const QModelIndex &index) const
{
    if( index.row() < 0 || index.row() >= rowCount() ) {
        return false;
    }
    return true;
}
